<template>
  <div class="container">
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	        <el-col :span="24" class="text-center">
	            <div class="title-wrapper">
	            <i class="el-icon-search el-icon--large"></i>
	            <h1 class="main-title">极端天气预警管理系统</h1>
	            <p class="sub-title">以严谨态度监测天气变化，用高效管理传递预警信号，让每一条预警信息，都成为守护平安的 “提前通知”</p>
	            </div>
	        </el-col>
	    </el-row>
    <!-- 查询区域 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="16">
        <el-form inline :model="timeRangeForm" class="time-range-form">
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="timeRangeForm.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="queryByTimeRange">查询</el-button>
            <el-button @click="resetTimeRange">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="8" class="text-right">
        <el-button type="primary" @click="openAddDialog">添加极端天气</el-button>
      </el-col>
    </el-row>

    <!-- 表格区域 -->
    <el-row>
      <el-table
        :data="tableData.slice((currentPage-1)*pageSize, currentPage*pageSize)"
        border
        style="width: 100%"
        height="450">
        <el-table-column 
          prop="weatherId" 
          label="极端天气编号" 
          width="200" 
          align="center">
        </el-table-column>
        <el-table-column 
          prop="weatherName" 
          label="极端天气名称" 
          width="200" 
          align="center">
        </el-table-column>
        <el-table-column 
          prop="warningType" 
          label="警告类型" 
          width="200" 
          align="center">
        </el-table-column>
        <el-table-column 
          prop="responseMeasures" 
          label="应对措施" 
          width="400" 
          align="center">
        </el-table-column>
        <el-table-column 
          prop="expectedTime" 
          label="预计发生时间" 
          align="center">
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button size="small" type="success" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.weatherId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-row type="flex" justify="center" style="margin-top: 10px;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10,20,50]"
          :page-size="pageSize"
          :total="tableData.length"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </el-row>
    </el-row>

    <!-- 添加对话框 -->
    <el-dialog 
      title="添加极端天气" 
      v-model="addDialogVisible" 
      width="50%">
      <el-form 
        :model="addForm" 
        ref="addFormRef" 
        :rules="rules" 
        label-width="120px">
        <el-form-item label="极端天气编号" prop="weatherId">
          <el-input v-model="addForm.weatherId" placeholder="请输入极端天气编号"></el-input>
        </el-form-item>
        <el-form-item label="极端天气名称" prop="weatherName">
          <el-input v-model="addForm.weatherName" placeholder="请输入极端天气名称"></el-input>
        </el-form-item>
        <el-form-item label="警告类型" prop="warningType">
          <el-input v-model="addForm.warningType" placeholder="请输入警告类型"></el-input>
        </el-form-item>
        <el-form-item label="应对措施" prop="responseMeasures">
          <el-input 
            v-model="addForm.responseMeasures" 
            type="textarea" 
            rows="3" 
            placeholder="请输入应对措施">
          </el-input>
        </el-form-item>
        <el-form-item label="预计发生时间" prop="expectedTime">
          <el-date-picker
            v-model="addForm.expectedTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog 
      title="编辑极端天气" 
      v-model="editDialogVisible" 
      width="50%">
      <el-form 
        :model="editForm" 
        ref="editFormRef" 
        :rules="rules" 
        label-width="120px">
        <el-form-item label="极端天气编号" prop="weatherId">
          <el-input v-model="editForm.weatherId" disabled></el-input>
        </el-form-item>
        <el-form-item label="极端天气名称" prop="weatherName">
          <el-input v-model="editForm.weatherName" placeholder="请输入极端天气名称"></el-input>
        </el-form-item>
        <el-form-item label="警告类型" prop="warningType">
          <el-input v-model="editForm.warningType" placeholder="请输入警告类型"></el-input>
        </el-form-item>
        <el-form-item label="应对措施" prop="responseMeasures">
          <el-input 
            v-model="editForm.responseMeasures" 
            type="textarea" 
            rows="3" 
            placeholder="请输入应对措施">
          </el-input>
        </el-form-item>
        <el-form-item label="预计发生时间" prop="expectedTime">
          <el-date-picker
            v-model="editForm.expectedTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdate">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 假设 axios 相关请求方法在 utils/request.js 中，需根据实际路径调整
import { post, get } from '@/utils/axios.js'

// 表格数据与分页
const currentPage = ref(1)
const pageSize = ref(5)
const tableData = ref([])

// 时间范围查询表单
const timeRangeForm = reactive({
  timeRange: []
})

// 添加对话框相关
const addDialogVisible = ref(false)
const addFormRef = ref(null)
const addForm = reactive({
  weatherId: '',
  weatherName: '',
  warningType: '',
  responseMeasures: '',
  expectedTime: ''
})

// 编辑对话框相关
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  weatherId: '',
  weatherName: '',
  warningType: '',
  responseMeasures: '',
  expectedTime: ''
})

// 表单验证规则
const rules = {
  weatherId: [
    { required: true, message: '请输入极端天气编号', trigger: 'blur' }
  ],
  weatherName: [
    { required: true, message: '请输入极端天气名称', trigger: 'blur' }
  ],
  warningType: [
    { required: true, message: '请输入警告类型', trigger: 'blur' }
  ],
  expectedTime: [
    { required: true, message: '请选择预计发生时间', trigger: 'blur' }
  ]
}

// 分页方法
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1 // 重置为第一页，保持分页逻辑一致性
}

function handleCurrentChange(val) {
  currentPage.value = val
}

// 获取所有极端天气数据
function getAllExtremeWeathers() {
  post('/sc/extremeweather/getAll', {}, (res) => {
    if (res.status === 1) {
      tableData.value = res.data
    } else {
      ElMessage.error('未查询到数据')
      tableData.value = []
    }
  })
}

// 按时间范围查询
function queryByTimeRange() {
  if (!timeRangeForm.timeRange || timeRangeForm.timeRange.length !== 2) {
    ElMessage.warning('请选择完整的时间范围')
    return
  }
  
  const params = {
    startTime: timeRangeForm.timeRange[0],
    endTime: timeRangeForm.timeRange[1]
  }
  
  get('/sc/extremeweather/byExpectedTime', params, (res) => {
    if (res.status === 1) {
      tableData.value = res.data
      ElMessage.success('查询成功')
    } else {
      ElMessage.error(res.msg || '查询失败')
    }
  })
}

// 重置时间范围查询
function resetTimeRange() {
  timeRangeForm.timeRange = []
  getAllExtremeWeathers()
}

// 打开添加对话框（增加表单重置逻辑，与示例风格一致）
function openAddDialog() {
  // 重置表单数据
  addForm.weatherId = ''
  addForm.weatherName = ''
  addForm.warningType = ''
  addForm.responseMeasures = ''
  addForm.expectedTime = ''
  
  addDialogVisible.value = true
  
  // 下一次DOM更新后清除验证状态
  nextTick(() => {
    if (addFormRef.value) {
      addFormRef.value.clearValidate()
    }
  })
}

// 处理添加
function handleAdd() {
  addFormRef.value.validate((valid) => {
    if (valid) {
      post('/sc/extremeweather/add', addForm, (res) => {
        if (res.status === 1) {
          ElMessage.success('添加成功')
          addDialogVisible.value = false
          getAllExtremeWeathers()
        } else {
          ElMessage.error(res.msg || '添加失败')
        }
      })
    }
  })
}

// 打开编辑对话框（优化数据赋值逻辑）
function openEditDialog(row) {
  // 复制行数据到编辑表单
  editForm.weatherId = row.weatherId
  editForm.weatherName = row.weatherName
  editForm.warningType = row.warningType
  editForm.responseMeasures = row.responseMeasures
  editForm.expectedTime = row.expectedTime
  
  editDialogVisible.value = true
  
  // 下一次DOM更新后清除验证状态
  nextTick(() => {
    if (editFormRef.value) {
      editFormRef.value.clearValidate()
    }
  })
}

// 处理更新
function handleUpdate() {
  editFormRef.value.validate((valid) => {
    if (valid) {
      post('/sc/extremeweather/updateById', editForm, (res) => {
        if (res.status === 1) {
          ElMessage.success('更新成功')
          editDialogVisible.value = false
          getAllExtremeWeathers()
        } else {
          ElMessage.error(res.msg || '更新失败')
        }
      })
    }
  })
}

// 处理删除
function handleDelete(weatherId) {
  ElMessageBox.confirm(
    `确定要删除编号为【${weatherId}】的极端天气记录吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    get('/sc/extremeweather/deleteById', { weatherId }, (res) => {
      if (res.status === 1) {
        ElMessage.success('删除成功')
        getAllExtremeWeathers()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {
    // 取消删除，不做额外操作
  })
}

// 页面加载时获取所有数据
onMounted(() => {
  getAllExtremeWeathers()
})
</script>

<style scoped>
.container {
  padding: 20px;
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.time-range-form {
  margin-bottom: 0;
}

.text-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

/* 对话框内容区滚动优化（与示例风格一致） */
.el-dialog__body {
  max-height: 500px;
  overflow-y: auto;
}
</style>